import axios, { AxiosRequestConfig, Method } from 'axios'
import { ElLoading, ElMessage } from 'element-plus'
import piniaStore from '@/store'

interface CancelConfig {
  url?: string
  method?: Method
  params?: any
  data?: any
  cancelToken?: any
}

interface ILoadingService {
  _count: number
  _target: any
}
interface AxiosOptions {
  // 是否开启取消重复请求, 默认为 true
  requestCancel?: Boolean
  // 是否显示加载动画,默认 false
  requestLoading?: Boolean
  // 提示报错信息,默认 true
  errorMessage?: Boolean
  // 简化返回值,默认 true
  dataFormat?: Boolean
}

const pendingMap = new Map()
const LoadingService: ILoadingService = {
  _count: 0,
  _target: null
}

function getPendingKey (config: CancelConfig) {
  let { url, method, params, data } = config
  if (typeof data === 'string' && data.indexOf('{') >= 0) { data = JSON.parse(data) } // response里面返回的config.data是个字符串对象
  return [
    url,
    method,
    JSON.stringify(params),
    JSON.stringify(data)
  ].join('&')
}

function addPending (config: CancelConfig) {
  const pendingKey = getPendingKey(config)
  config.cancelToken =
    config.cancelToken ||
    new axios.CancelToken((cancel) => {
      if (!pendingMap.has(pendingKey)) {
        pendingMap.set(pendingKey, cancel)
      }
    })
}

function removePending (config: CancelConfig) {
  const pendingKey = getPendingKey(config)
  if (pendingMap.has(pendingKey)) {
    const cancelToken = pendingMap.get(pendingKey)
    cancelToken(pendingKey)
    pendingMap.delete(pendingKey)
  }
}

function closeLoading (_options: AxiosOptions) {
  if (_options.requestLoading && LoadingService._count > 0) { LoadingService._count-- }
  if (LoadingService._count === 0) {
    LoadingService._target.close()
    LoadingService._target = null
  }
}

function httpErrorStatusHandle (error: any) {
  // 处理被取消的请求
  if (axios.isCancel(error)) { return console.error('请求的重复请求：' + error.message) }
  let message = ''
  if (error.message.includes('timeout')) message = '网络请求超时！'
  if (error.message.includes('Network')) { message = window.navigator.onLine ? '服务端异常！' : '您断网了！' }
  if (error.response.data?.error_description || error.response.data?.error?.message) {
    message = error.response.data.error_description || error.response.data.error.message + '   ' + (error.response.data.error.details || '')
  }
  if (error && error.response && !message) {
    switch (error.response.status) {
      case 302:
        message = '接口重定向了！'
        break
      case 400:
        message = '参数不正确！'
        break
      case 401:
        message = '您未登录，或者登录已经超时，请先登录！'
        break
      case 403:
        message = '您没有权限操作！'
        break
      case 404:
        message = `请求地址出错: ${error.response.config.url}`
        break // 在正确域名下
      case 408:
        message = '请求超时！'
        break
      case 409:
        message = '系统已存在相同数据！'
        break
      case 500:
        message = '服务器内部错误！'
        break
      case 501:
        message = '服务未实现！'
        break
      case 502:
        message = '网关错误！'
        break
      case 503:
        message = '服务不可用！'
        break
      case 504:
        message = '服务暂时无法访问，请稍后再试！'
        break
      case 505:
        message = 'HTTP版本不受支持！'
        break
      default:
        message = '异常问题，请联系管理员！'
        break
    }
  }
  ElMessage({
    type: 'error',
    message
  })
}

function createAxios (
  axiosConfig: AxiosRequestConfig<any>,
  customOptions?: AxiosOptions
) {
  const service = axios.create({
    baseURL: import.meta.env.VITE_BASEURL
  })
  // 默认配置
  const defaultOptions = {
    requestCancel: true,
    requestLoading: false,
    errorMessage: true,
    dataFormat: true
  }
  const options = Object.assign(defaultOptions, customOptions)

  service.interceptors.request.use(
    (config) => {
      removePending(config)
      options.requestCancel && addPending(config)
      if (options.requestLoading) {
        LoadingService._count++
        if (LoadingService._count === 1) {
          LoadingService._target = ElLoading.service({
            lock: true,
            text: '加载中...',
            background: 'rgba(0, 0, 0, 0.7)'
          })
        }
      }
      const token = piniaStore.userStore.token
      if (token && typeof window !== 'undefined') {
        config.headers &&
          (config.headers.authorization = 'Bearer ' + token)
      }
      config.headers &&
        (config.headers['accept-language'] = 'zh-Hans')
      config.headers &&
          (config.headers['X-Requested-With'] = 'XMLHttpRequest')
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )

  service.interceptors.response.use(
    (response) => {
      const { url, method, params, data } = response.config
      const config: CancelConfig = {
        url,
        method,
        params,
        data
      }
      removePending(config)
      options.requestLoading && closeLoading(options)
      // const res = options.dataFormat ? response.data : response
      // return res
      return response
    },
    (error) => {
      error.config && removePending(error.config)
      options.requestLoading && closeLoading(options)
      options.errorMessage && httpErrorStatusHandle(error)
      return Promise.reject(error.response.data)
    }
  )
  return service(axiosConfig)
}

// export default createAxios
export default <T>(
  axiosConfig: AxiosRequestConfig<any>,
  customOptions?: AxiosOptions
) => {
  return createAxios(axiosConfig, customOptions).then(res => {
    return res.data as T
  })
}
